//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////

using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;

#if Gdmp || Gnuf
using Glodon.Gdmp.DB;
using Glodon.Gdmp.UI;
#elif Gap
using Glodon.Gap.DB;
using Glodon.Gap.UI;
#endif
using Glodon.Lookup.Lookup.Core;
using Glodon.Lookup.Utils;

namespace Glodon.Lookup.Commands
{
    public abstract class CommandBase : IExternalCommand
    {
        protected abstract void Execute();
        public Result Execute(UIDocument document)
        {
            if (document == null)
            {
                ExceptionUtils.ShowExceptionMessage("请先打开或新建一个文档");
                return Result.Succeeded;
            }
            InitailizeAsync().Wait();
            Execute();
            AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomainAssemblyResolve;
            return Result.Succeeded;
        }

        protected async Task InitailizeAsync()
        {
            //备用，屏蔽不Show的类别。
            GlodonAPI.CategoriesCannotShow = new ReadOnlyCollection<UniIdentity>(new List<UniIdentity>() { });

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                Exception ex = (Exception)e.ExceptionObject;
                ExceptionUtils.ShowExceptionMessage(ex);
            };
            TaskScheduler.UnobservedTaskException += HandleUnobservedTaskException;

            //依赖注入。
            await Host.StartHost();
        }
        static void HandleUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            // 处理异常
            foreach (Exception ex in e.Exception.InnerExceptions)
            {
                ExceptionUtils.ShowExceptionMessage(ex);
            }
            // 通知垃圾回收器，这个异常已经被处理
            e.SetObserved();
        }

        #region 解决System.Runtime.CompilerServices.Unsafe.dll加载问题
        private const string MYPROBINGFOLDER = "ProbingFolder";
        private Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
        {
            var assyName = new AssemblyName(args.Name);

            var newPath = Path.Combine(MYPROBINGFOLDER, assyName.Name);
            if (!newPath.EndsWith(".dll"))
            {
                var location = Assembly.GetAssembly(GetType()).Location;
                var assemblyFolder = Path.GetDirectoryName(location);
                newPath = Path.Combine(assemblyFolder, newPath + ".dll");
            }
            if (File.Exists(newPath))
            {
                var assy = Assembly.LoadFile(newPath);
                return assy;
            }
            return null;
        }
        #endregion
    }
}
